﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SQLite;
using DialogsEditor.DAO;

namespace DialogsEditor
{
    public partial class LoadDialogForm : Form
    {
        private int currentSelected = -1;
        private Form1 main;

        private Label title = new Label();
        private Label trigger = new Label();
        private Label text = new Label();

        public LoadDialogForm()
        {
            InitializeComponent();
            CenterToParent();
            LoadDialogs();
            Focus();
        }

        public LoadDialogForm(Form1 form)
        {
            InitializeComponent();
            CenterToParent();
            LoadDialogs();
            main = form;
        }

        public void LoadDialogs()
        {
            using (SQLiteConnection conn = ConnFactory.getInstancia().GetConnDialog())
            {
                SQLiteDataReader reader = null;
                try
                {
                    conn.Open();
                    string select = "select id, title, trig, text, idnextdialog from dialog where isproject";

                    SQLiteCommand cmd = new SQLiteCommand(select, conn);

                    reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        DialogEntity d = new DialogEntity(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt32(4));
                        Form1.LoadDialogsEntity.Add(d);
                    }

                    //é o load mais recente
                    NewDialogForm.anyNewDialog = false;
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Erro de conexão");
                }
                catch (SQLiteException mysqlError)
                {
                    MessageBox.Show("Erro de acesso ao BD: " + mysqlError.Message, "Error");
                }
                finally
                {
                    if (reader != null) reader.Close();
                    conn.Close();
                }

            }
        }

        private void ShowEntity()
        {
            
            //criar uma lista de dialogos com o que eu pego daqui....
            // e colocar numa lista de dialogos no form inicial
            tbDialogs.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
            tbDialogs.RowCount = Form1.LoadDialogsEntity.Count+1;

            title.Text = "Title";
            trigger.Text = "Trigger";
            text.Text = "Text";

            tbDialogs.Controls.Add(title, 0, 0);
            tbDialogs.Controls.Add(trigger, 1, 0);
            tbDialogs.Controls.Add(text, 2, 0);
            for(int line = 0; line < Form1.LoadDialogsEntity.Count; line++)
            {
                
                DialogEntity d = Form1.LoadDialogsEntity[line];

                //d.trigger.Text = UtilsDAO.GetNameTigger(d.idTrig);

                tbDialogs.Controls.Add(d.title, 0, line+1);
                tbDialogs.Controls.Add(d.trigger, 1, line+1);
                tbDialogs.Controls.Add(d.text, 2, line+1);
            }
        }

        private void SelectDialogFromTable(object sender, MouseEventArgs e)
        {
            Point p = GetRowColIndex(tbDialogs, tbDialogs.PointToClient(Cursor.Position));
            if (p.IsEmpty) return;
            currentSelected = p.Y;

            for (int i = 0; i < tbDialogs.ColumnCount; i++)
            {
                for (int j = 0; j < tbDialogs.RowCount; j++)
                {
                    Control control = tbDialogs.GetControlFromPosition(i, j);
                    if (j == currentSelected)
                    {
                        control.BackColor = Color.Blue;
                    }
                    else
                        control.BackColor = Color.Transparent;
                }
            }
        }

        Point GetRowColIndex(TableLayoutPanel tpl, Point point)
        {
            if (point.X > tpl.Width || point.Y > tpl.Height)
                return Point.Empty;

            int w = tpl.Width;
            int h = tpl.Height;
            int[] widths = tpl.GetColumnWidths();

            int i;
            for (i = widths.Length - 1; i >= 0 && point.X < w; i--)
                w -= widths[i];
            int col = i +1;

            int[] heights = tpl.GetRowHeights();
            for (i = heights.Length - 1; i > 0 && point.Y < h; i--)
                h -= heights[i];

            int row = i +1;

            return new Point(col, row);
        }

        public void ShowLoadDialogs()
        {
            if (NewDialogForm.anyNewDialog)
            {
                tbDialogs.Controls.Clear();
                Form1.LoadDialogsEntity.Clear();
                tbDialogs.RowCount = 0;
                LoadDialogs();
            }
            ShowEntity();
            Show();
            
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {

            if (currentSelected <= 0)
            {
                MessageBox.Show("Você deve selecionar um dialogo");
                return;
            }

            //adicionar o dialogo lá na pagina principal
            main.ClearControlDialog();
            Form1.CurrentProject = Form1.LoadDialogsEntity[currentSelected - 1];
            Form1.CurrentDialogs = DialogEditorDAO.LoadDialogs(Form1.CurrentProject);

            foreach (DialogEntity d in Form1.CurrentDialogs)
            {
                foreach (DialogEntity dE in Form1.CurrentDialogs)
                {
                    if (d == dE) continue;

                    if (d.idNextDialog == dE.GetID())
                        Form1.CurrentLinks.Add(new Line(d, dE));
                }
            }

            //if (!Form1.CurrentDialogs.Contains(Form1.LoadDialogsEntity[currentSelected]))
            //    Form1.CurrentDialogs.Add(Form1.LoadDialogsEntity[currentSelected]);
            Hide();
            ClearSelected();
            currentSelected = -1;
            if (main != null)
                main.ShowFormDialogs();

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Hide();
            ClearSelected();
            currentSelected = -1;
        }

        private void ClearSelected()
        {
            if (currentSelected < 0) return;
            for (int i = 0; i < tbDialogs.ColumnCount; i++)
            {
                Control control = tbDialogs.GetControlFromPosition(i, currentSelected);
                if (control != null)
                    control.BackColor = Color.Transparent;
            }
        }
    }
}
